package top.lbqaq.servlet;

import top.lbqaq.vo.Product;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet(name = "Servlet6", urlPatterns = {"/Servlet6"})
public class Servlet6 extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        HttpSession session = request.getSession();
        if (request.getParameter("type") != null && request.getParameter("type").equals("cls")) {
            //session.invalidate();
            session.removeAttribute("plist");
            session.setAttribute("sum", "0");
        }
        List<Product> mylist = (List<Product>) session.getAttribute("plist");
        String ssum = (String) session.getAttribute("sum");
        String sname = request.getParameter("sname");
        String price = request.getParameter("price");
        String num = request.getParameter("num");
        if (sname != null && !sname.equals("") && price != null && num != null) {
            Product myProduct = new Product();
            myProduct.setSname(sname);
            myProduct.setPrice(Integer.parseInt(price));
            myProduct.setNum(Integer.parseInt(num));
            if (mylist == null) {
                mylist = new ArrayList<>();
            }
            mylist.add(myProduct);
            session.setAttribute("plist", mylist);
            if (ssum == null) {
                ssum = "0";
            }
            ssum = (Integer.parseInt(ssum) + Integer.parseInt(price) * Integer.parseInt(num)) + "";

            session.setAttribute("sum", ssum);
        }
        response.sendRedirect("6.jsp");
        //request.getRequestDispatcher("test12.jsp").forward(request,response);
    }
}
